package com.keya.config;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class UrlMatcherConfig {
    @Resource
    IgnoreTokenUrlConfig ignoreTokenUrlConfig;
    private static final String TMP_PLACEHOLDER = "@@@@@#####$$$$$";

    private List<Pattern> valueToPatterns() {
        List<Pattern> patterns = new ArrayList<>();
        List<String> patternItems = ignoreTokenUrlConfig.getUrl();
        for (String patternItem : patternItems) {
            patternItem = patternItem.trim();
            if ("".equals(patternItem)) {
                continue;
            }
            patternItem = patternItem.replace("**", TMP_PLACEHOLDER);
            patternItem = patternItem.replace("*", "[^/]*?");//替换*
            patternItem = patternItem.replace(TMP_PLACEHOLDER, "**");
            patternItem = patternItem.replace("**", ".*?");//替换**
            patterns.add(Pattern.compile(patternItem));
        }

        return patterns;
    }

    public boolean matches(String url) {
        return matches(valueToPatterns(), url);
    }

    private boolean matches(List<Pattern> patterns, String url) {
        if (patterns == null || patterns.size() == 0) {
            return false;
        }
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }

    public static boolean matches(String patternItem, String url) {
        patternItem = patternItem.trim();
        if ("".equals(patternItem)) {
            return false;
        }
        patternItem = patternItem.replace("**", TMP_PLACEHOLDER);
        patternItem = patternItem.replace("*", "[^/]*?");//替换*
        patternItem = patternItem.replace(TMP_PLACEHOLDER, "**");
        patternItem = patternItem.replace("**", ".*?");//替换**
        Pattern pattern = Pattern.compile(patternItem);
        Matcher matcher = pattern.matcher(url);
        return matcher.matches();
    }
}
